/*
 * Copyright (c) 2002-2003 by OpenSymphony
 * All rights reserved.
 */
package org.jackysoft.workflow.util;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.jackysoft.entity.OsStep;
import org.jackysoft.entity.WorkflowRunner;
import org.jackysoft.service.OsVariableService;
import org.jackysoft.service.OsWorkflowRunnerService;
import org.jackysoft.workflow.Condition;

/**
 * Simple utility condition that returns true if the current step's status is
 * the same as the required argument "status". Looks at ALL current steps unless
 * a stepId is given in the optional argument "stepId".
 * 
 * @author <a href="mailto:plightbo@hotmail.com">Pat Lightbody</a>
 */
public class StatusCondition implements Condition {
	// ~ Methods
	// ////////////////////////////////////////////////////////////////

	@Override
	public boolean passesCondition(Map transientVars, Map args,
			OsVariableService vservice) {
		Object ost = args.get("status");
		if (ost == null)
			throw new IllegalStateException("请设置 status 参数");
		String status = ost.toString();
		int stepId = 0;
		Object stepIdVal = args.get("stepId");

		if (stepIdVal != null) {
			try {
				stepId = Integer.parseInt(stepIdVal.toString());
			} catch (Exception ex) {
			}
		}

		WorkflowRunner entry = (WorkflowRunner) transientVars.get("entry");
		OsWorkflowRunnerService store = (OsWorkflowRunnerService) transientVars.get("store");
		Collection<OsStep> currentSteps = store.findCurrentSteps(entry.getId());

		if (stepId == 0) {
			for (Iterator<OsStep> iterator = currentSteps.iterator(); iterator
					.hasNext();) {
				OsStep step = iterator.next();

				if (status.equals(step.getStatus())) {
					return true;
				}
			}
		} else {
			for (Iterator<OsStep> iterator = currentSteps.iterator(); iterator
					.hasNext();) {
				OsStep step = iterator.next();

				if (stepId == step.getId()) {
					if (status.equals(step.getStatus())) {
						return true;
					}
				}
			}
		}

		return false;
	}
}
